package graphics;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;

import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;

import core.Message;
import core.ResultSetTableModel;
import core.UtilityFunctions;
import db.DBConnection;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class VisualizzaClientiJPanel extends javax.swing.JPanel {
	private JScrollPane jScrollPaneTable;
	private JButton cancellaClientejButton;
	private JLabel filterjLabel;
	private JTextField filterjTextField;
	private JPanel buttonsjPanel;
	private JButton nuovoClientejButton;
	public JButton visualizzaSelezionajButton;
	private JPanel filterjPanel;
	private JTable clientijTable;
	private DBConnection dbCon;
	
	public AbstractAction buttonSelectAbstractAction;
	
	boolean select = false;
	
	String queryFilter = "";

	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}


	/**
	* Auto-generated main method to display this 
	* JPanel inside a new JFrame.
	*/
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.getContentPane().add(new VisualizzaClientiJPanel(false));
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
		frame.setLocationRelativeTo(null);
	}
	
	public VisualizzaClientiJPanel(boolean select) {
		super();
		try {
			dbCon = new DBConnection();
			this.select = select;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Message message = new Message(new JFrame());
			message.errorLocked();
		}
		initGUI();
	}
	
	private void initGUI() {
		try {
			BoxLayout thisLayout = new BoxLayout(this, javax.swing.BoxLayout.Y_AXIS);
			this.setLayout(thisLayout);
			this.setPreferredSize(new java.awt.Dimension(816, 469));
			{
				filterjPanel = new JPanel();
				this.add(filterjPanel);
				filterjPanel.setPreferredSize(new java.awt.Dimension(816, 38));
				{
					filterjLabel = new JLabel();
					filterjPanel.add(filterjLabel);
					filterjLabel.setText("Filtra in base a chiave (Cognome):");
				}
				{
					filterjTextField = new JTextField();
					filterjPanel.add(filterjTextField);
					filterjTextField.setPreferredSize(new java.awt.Dimension(258, 28));
					filterjTextField.addKeyListener(new KeyListener() {
						
						@Override
						public void keyTyped(KeyEvent arg0) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void keyReleased(KeyEvent arg0) {
							// TODO Auto-generated method stub
							queryFilter = "WHERE LOWER(COGNOME) LIKE '" + filterjTextField.getText().toLowerCase()+"%'";
							initializeTable();
							if(arg0.getKeyCode() == KeyEvent.VK_ENTER)
							{
								filterjTextField.transferFocus();	
							}
							else if(arg0.getKeyCode() == KeyEvent.VK_F2)
							{
								nuovoClientejButton.doClick();
							}
						}
						
						@Override
						public void keyPressed(KeyEvent arg0) {
							// TODO Auto-generated method stub
							
						}
					});
				}
			}
			{
				jScrollPaneTable = new JScrollPane();
				this.add(jScrollPaneTable);
				jScrollPaneTable.setPreferredSize(new java.awt.Dimension(816, 363));
				{
					initializeTable();
					//clientijTable.setRowSelectionInterval(0, 0);
				}
			}
			{
				buttonsjPanel = new JPanel();
				this.add(buttonsjPanel);
				buttonsjPanel.setPreferredSize(new java.awt.Dimension(816, 42));
				{
					visualizzaSelezionajButton = new JButton();
					buttonsjPanel.add(visualizzaSelezionajButton);
					if(select)
						this.setSelezionaClientiJButton();
					else
						this.setVisualizzaClientiJButton();
				}
				{
					cancellaClientejButton = new JButton();
					buttonsjPanel.add(cancellaClientejButton);
					cancellaClientejButton.setText("Cancella Cliente (CANC)");
					cancellaClientejButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/Delete.png")));
					cancellaClientejButton.addActionListener(new ActionListener() {
						
						@Override
						public void actionPerformed(ActionEvent arg0) {
							// TODO Auto-generated method stub
							cancellaCliente();
						}
					});
				}
				{
					nuovoClientejButton = new JButton();
					buttonsjPanel.add(nuovoClientejButton);
					nuovoClientejButton.setText("Aggiungi Nuovo Cliente (F2)");
					nuovoClientejButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/Add.png")));
					nuovoClientejButton.setPreferredSize(new java.awt.Dimension(209, 43));
					nuovoClientejButton.addActionListener(new ActionListener() {
						
						@Override
						public void actionPerformed(ActionEvent e) {
							// TODO Auto-generated method stub
							JFrame frame = new JFrame();
							frame.getContentPane().add(new NuovoClienteJPanel());
							frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
							frame.pack();
							frame.setTitle("Inserisci Nuovo Cliente | eOrder - Software per la gestione degli ordini sviluppato da Marco Cozza");
							frame.setVisible(true);
							frame.setLocationRelativeTo(null);
						}
					});
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void initializeTable()
	{
		TableModel clientijTableModel = this.searchIntoDb();
		clientijTable = new JTable();
		jScrollPaneTable.setViewportView(clientijTable);
		this.setModel(clientijTableModel);
		
		//aggiunge il keyListener
		clientijTable.addKeyListener(new KeyListener() {
			
			@Override
			public void keyTyped(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void keyReleased(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void keyPressed(KeyEvent arg0) {
				// TODO Auto-generated method stub
				if(arg0.getKeyCode() == KeyEvent.VK_F12)
				{
					visualizzaSelezionajButton.doClick();
				}
				else if(arg0.getKeyCode() == KeyEvent.VK_DELETE)
				{
					cancellaClientejButton.doClick();
				}
				else if(arg0.getKeyCode() == KeyEvent.VK_F2)
				{
					nuovoClientejButton.doClick();
				}
				
			}
		});
	}
	
	private TableModel searchIntoDb() {
		String query = 
			"SELECT CodiceCliente, CodiceFiscale, PartitaIva, Nome, Cognome, RagioneSociale, Comune " +
			"FROM Cliente " + queryFilter + ";";
		Statement st;
		ResultSet rs;
		core.ResultSetTableModel rstModel;
		try {
			st = dbCon.getCon().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			rs = st.executeQuery(query);
			rstModel = new core.ResultSetTableModel(rs);
			return rstModel;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//message.customError("Impossibile leggere i dati della tabella", "Visualizza Clienti");
			TableModel defaultModel = 
				new DefaultTableModel(
						new String[][] { },
						new String[] { "", "", "", "", "", "", "", "", "", "", "" });
			return defaultModel;
		}
	}
	
	private void setModel(TableModel clientijTableModel) {
		clientijTable.setModel(clientijTableModel);
		/*
		jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		jTable1.setRowSorter(new TableRowSorter<TableModel> (jTable1Model));
		*/
		{
			TableColumnModel cm = clientijTable.getColumnModel();
			TableColumn columnCodice = cm.getColumn(0);
			columnCodice.setResizable(false);
			columnCodice.setMinWidth(40);
			columnCodice.setMaxWidth(40);
			TableColumn columnPartitaIva = cm.getColumn(2);
			columnPartitaIva.setMinWidth(110);
			columnPartitaIva.setMaxWidth(110);
			TableColumn columnCodFiscale = cm.getColumn(1);
			columnCodFiscale.setMinWidth(140);
			columnCodFiscale.setMaxWidth(140);
			TableColumn columnRagioneSociale = cm.getColumn(5);
			columnRagioneSociale.setResizable(true);
			columnRagioneSociale.setMinWidth(130);
			columnRagioneSociale.setMaxWidth(230);
			
			for(int i=2; i<7 && i!=5; i++) {
				cm.getColumn(i).setMinWidth(80);
			} 
		}
	}
	
	public void setSelezionaClientiJButton()
	{
		visualizzaSelezionajButton.setText("Seleziona Cliente (F12)");
		visualizzaSelezionajButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/Select.png")));
		visualizzaSelezionajButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				System.out.println(clientijTable.getValueAt(clientijTable.getSelectedRow(), 0));
			}
		});
	}
	
	public void setVisualizzaClientiJButton()
	{
		visualizzaSelezionajButton.setText("Visualizza (F12)");
		visualizzaSelezionajButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/view.png")));
		visualizzaSelezionajButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				JFrame frame = new JFrame();
				frame.getContentPane().add(new VisualizzaClienteJPanel(Integer.parseInt(clientijTable.getValueAt(clientijTable.getSelectedRow(), 0).toString())));
				frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
				frame.pack();
				frame.setTitle("Visualizza Cliente Cod. " + Integer.parseInt(clientijTable.getValueAt(clientijTable.getSelectedRow(), 0).toString()) + " | eOrder - Software per la gestione degli ordini sviluppato da Marco Cozza");
				frame.setVisible(true);
				frame.setLocationRelativeTo(null);
			}
		});
	}

	/**
	 * @return the clientijTable
	 */
	public JTable getClientijTable() {
		return clientijTable;
	}

	/**
	 * @return the visualizzaSelezionajButton
	 */
	public JButton getVisualizzaSelezionajButton() {
		return visualizzaSelezionajButton;
	}
	
	public void setButtonVisualizzaSelezionaIcon()
	{
		visualizzaSelezionajButton.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/Select.png")));
	}
	
	private void cancellaCliente()
	{
		String queryControlloOrdiniConCliente = "SELECT CodiceOrdine FROM ORDINE WHERE Cliente = ?";
		String deleteRowFirst = "DELETE RigaOrdine WHERE CodiceOrdine = ?";
		String deleteQuery = "DELETE Cliente WHERE CodiceCliente = ?";
		String deleteOrdine = "DELETE Ordine WHERE CodiceOrdine = ?";
		
		UtilityFunctions ut = new UtilityFunctions();
		
		Message message = new Message(new JFrame());
		
		if(message.doElimination("Sei sicuro di voler cancellare il cliente selezionato? In questo modo eliminerai anche tutti gli ordini a lui associati"))
		{
			try {
				
				ResultSet res = ut.executeParametricQuerySingleParameter(dbCon, queryControlloOrdiniConCliente, clientijTable.getValueAt(clientijTable.getSelectedRow(), 0).toString());
				
				int codiceOrdine;
				while(res.next())
				{
					codiceOrdine = res.getInt("CodiceOrdine");
					ut.executeParametricUpdateSingleParameter(dbCon, deleteRowFirst, codiceOrdine+"");
					ut.executeParametricUpdateSingleParameter(dbCon, deleteOrdine, codiceOrdine+"");
				}
			
				ut.executeParametricUpdateSingleParameter(dbCon, deleteQuery,  clientijTable.getValueAt(clientijTable.getSelectedRow(), 0).toString());
				
				
				message.info("Cancellazione cliente avvenuta correttamente");
				
				this.initializeTable();
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				message.errorMessage("Cancellazione cliente non avvenuta, riprovare", "Errore Cancellazione");
			}
		}
		
	}


}
